package com.basic.business.wechat;

import cn.hutool.http.Header;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.basic.business.common.constants.Constants;
import com.basic.business.common.utils.DateUtils;
import com.basic.business.order.domain.TOrdersMain;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.*;

/**
 * 微信机器人工具类
 *
 * @author zhaoxy_jn@163.com
 */
@Component
public class WeChatUtil {

    /**
     * 调用微信机器人socket地址，发送微信消息
     */
    private static void sendWeChatMsg(Map<String, Object> body){
        HttpUtil.createPost(Constants.WECHAT_KEY)
                .header(Header.CONTENT_TYPE, "application/json").header(Header.ACCEPT_CHARSET, "utf-8")
                .body(JSON.toJSONString(body))
                .execute()
                .body();
    }



    /**
     * 发送文本消息
     */
    public static void sendTextMsg() {
        Map<String, Object> sendMap = new HashMap<>();
        //设置消息类型 txt文本
        sendMap.put("msgtype", "text");
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("content", "测试机器人推送消息");
        sendMap.put("text", contentMap);
        sendWeChatMsg(sendMap);
    }

    /**
     * 发送markdown文本消息
     */
    public static void sendMarkDownTextMsg(String type, TOrdersMain ordersMain, String delMsg) {
        Map<String, Object> sendMap = new HashMap<>();
        //设置消息类型 markdown文本
        sendMap.put("msgtype", "markdown");
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("content", "【温馨提示】\n自动处理程序反馈消息如下，请相关人员注意！！！\n" +
                " >类型：<font color=\"warning\">" + type + "</font>\n" +
                " >时间：<font color=\"comment\">" + DateUtils.timestampToDate(ordersMain.getUpdTime()) + "</font>\n" +
                " >删包：<font color=\"warning\">" + delMsg + "</font>\n" +
                " >店铺名称：<font color=\"info\">" + ordersMain.getShopName() + "</font>\n" +
                " >订单金额：<font color=\"warning\">" + ordersMain.getPayAmount() + "</font>\n" +
                " >内部单号：" + ordersMain.getShortId() + "\n" +
                " >系统单号：" + ordersMain.getSid() + "\n" +
                " >平台单号：" + ordersMain.getTid());
        sendMap.put("markdown", contentMap);
        sendWeChatMsg(sendMap);
    }

    /**
     * 发送图片消息
     */
    public static void sendImageMsg() {
        String url = "D:\\Program Files\\JcProjects\\dotest\\src\\main\\resources\\static\\test.png";
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("msgtype", "image");
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("md5", getMd5(url));
        contentMap.put("base64", getBase64(url).replaceAll("\r|\n", ""));
        sendMap.put("image", contentMap);
        sendWeChatMsg(sendMap);
    }

    /**
     * 发送图文消息
     */
    public static void sendImageAndTxtMsg() {
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("msgtype", "news");
        Map<String, Object> contentMap = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> obj = new HashMap<>();
        obj.put("title", "小目标青年的博客");
        obj.put("description", "大家给他点点赞！");
        obj.put("url", "https://blog.csdn.net/qq_35387940");
        obj.put("picurl", "https://img-blog.csdnimg.cn/6bc435ac39514cb780739ea1cc34c409.png");
        list.add(obj);
        contentMap.put("articles", list);
        sendMap.put("news", contentMap);
        sendWeChatMsg(sendMap);
    }


    /**
     * 图片转为base64编码
     */
    public static String getBase64(String imgFile) {
        InputStream in = null;
        byte[] data = null;
        //  读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }

    /**
     * 获取文件的MD5值
     *
     * @param path
     * @return
     */
    public static String getMd5(String path) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(path);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                md5.update(buffer, 0, len);
            }
            fis.close();
            byte[] byteArray = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : byteArray) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}